#include "RegLinks.h"
#include "Region.h"

namespace Torch {

RegLinks::RegLinks(Region *iR1,Region *iR2) {
    
        R1= new Region();
        R2= new Region();
        R1=iR1;
	R2=iR2;
	Label1=R1->GetLabel();
	Label2=R2->GetLabel();
	
	UpDate();
	
}


void RegLinks::UpDate() {

	int iMu1,iSigma1,iMaxmin1,iNbPixel1;
	int iMu2,iSigma2,iMaxmin2,iNbPixel2;
	int Min=0,Max=0;
	
	double dSig_part1,dSig_part2,dSig;

	R1->GetParam(&iMu1,&iSigma1,&iMaxmin1,&iNbPixel1);
	R2->GetParam(&iMu2,&iSigma2,&iMaxmin2,&iNbPixel2);

	Min=R1->GetMin();
	if(Min > R2->GetMin())
		Min=R2->GetMin();

	Max=R1->GetMax();
	if(Max < R2->GetMax())
		Max=R2->GetMax();  

	NbPixel=iNbPixel1 + iNbPixel2;

	
	Mu=(iNbPixel1 * iMu1 + iNbPixel2 * iMu2)/(iNbPixel1 + iNbPixel2);

	Moydiff= iMu1 - iMu2;

       if(Moydiff<0) 
	  Moydiff=(-1)*Moydiff;

	Maxmin =  Max-Min;

	dSig_part1=(iNbPixel1*(iSigma1 + iMu1*iMu1))/(iNbPixel1+iNbPixel2);
	dSig_part2=(iNbPixel2*(iSigma2 + iMu2*iMu2))/(iNbPixel1+iNbPixel2);
	dSig=dSig_part1+dSig_part2;

	if(dSig<0)
		dSig=0;
	dSig-=(Mu*Mu);

	Sigma=dSig;


}

void RegLinks::GetParam(int *iMu,int *iSigma ,int *iMaxmin ,int *iMoydiff ,int *iNbPixel) {
    
	*iMu=Mu;
	*iSigma=Sigma;
	*iMaxmin=Maxmin;
	*iMoydiff=Moydiff;
	*iNbPixel=NbPixel;

}


void RegLinks::SetRegLinks(int iChoix,Region *R) {
    
	if(iChoix==1)
	{
		for(int i=0;i<R2->GetNbVoisin();i++)
		{
			if(R2->GetVoisin(i)==R1->GetLabel())
			{
				R2->SetVoisin(i,R->GetLabel());
			}
		}
		R1=R;
		Label1=R1->GetLabel();
		
	}
	else
	{
		for(int i=0;i<R1->GetNbVoisin();i++)
		{
			if(R1->GetVoisin(i)==R2->GetLabel())
			{
				R1->SetVoisin(i,R->GetLabel());
			}
		}
		R2=R;
		Label2=R2->GetLabel();
		
	}
}

void RegLinks::SupVoisin(bool bChoix,int RegionASupprimer) {
    
	if(bChoix)
	{
		for(int i=0;i<R2->GetNbVoisin();i++)
		{
			if(R2->GetVoisin(i)==RegionASupprimer)
				R2->SupVoisin(i);
		}
	}
	else
		for(int i=0;i<R1->GetNbVoisin();i++)
			if(R1->GetVoisin(i)==RegionASupprimer)
				R1->SupVoisin(i);
		

}
}
